<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title></title>
  </head>
  <body>
    <div id="app">
      <div>提问：<input v-model="question" /></div>
      <div>{{ answer }}</div>
    </div>

    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>

    <script>
      const { createApp, reactive, ref, watch } = Vue;

      const app = createApp({
        setup() {
          const question = ref("编程段子?");
          const answer = ref("");

          let timeId;

          // `watch` 默认是懒执行的：仅当数据源变化时，才会执行回调。
          // 通过传入 `immediate: true` 选项来强制侦听器的回调立即执行
          watch(
            question,
            (newQuestion, oldQuestion) => {
              console.log("oldQuestion", oldQuestion);
              console.log("newQuestion", newQuestion);
              if (newQuestion.indexOf("?") > -1) {
                answer.value = "思考中...";

                timeId && clearTimeout(timeId);
                timeId = setTimeout(
                  () => (answer.value = `结果为：${newQuestion}`),
                  1000
                );
              }
            },
            {
              immediate: true,
            }
          );

          return {
            question,
            answer,
          };
        },
      });

      app.mount("#app");
    </script>
  </body>
</html>
